/*
 * SimpleBarrier.java
 *
 * Created on August 3, 2005, 10:48 PM
 *
 * From "Multiprocessor Synchronization and Concurrent Data Structures",
 * by Maurice Herlihy and Nir Shavit.
 *
 * This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.
 * http://i.creativecommons.org/l/by-sa/3.0/us/88x31.png
 */

package barrier.simpleBarrier;
import java.util.concurrent.atomic.AtomicInteger;

import barrier.Barrier;

/**
 * This implementation is intentionally incorrect!
 * @author Maurice Herlihy
 */
public class SimpleBarrier implements Barrier {
  AtomicInteger count;
  int size;
  /**
   * 
   * @param n 
   */
  public SimpleBarrier(int n) {
    this.count = new AtomicInteger(n);
    this.size = n;
  }
  @Override
  public void await() {
    int position = count.getAndDecrement();
    if (position == 1) { // If I'm last ...
      count.set(size);	 // reset for next use
    } else {			 // otherwise spin
      while (count.get() != 0) {}
    }
  }
}
